﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace INNOVACALL.Framework.Common.Serialization
{
    public abstract class _Serialisation_Base
    {
        #region "Serialisation et désérialisation"
        /// <summary>
        /// Sérialisation d'une classe (attention, elle doit être taguée [Serializable]
        /// </summary>
        /// <param name="Obj"></param>
        /// <returns></returns>
        public static String Serialize(Object Obj)
        {
            XmlSerializer serializer = new XmlSerializer(Obj.GetType());
            StringBuilder sb = new StringBuilder();
            StringWriter writer = new StringWriter(sb);
            serializer.Serialize(writer, Obj);
            writer.Close();
            writer.Dispose();
            return sb.ToString();
        }
        /// <summary>
        /// Désérialisation d'une chaine de caractères vers le type T
        /// </summary>
        /// <param name="str"></param>
        /// <param name="t"></param>
        /// <returns></returns>
        public static T Deserialize<T>(String str)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            StringReader reader = new StringReader(str);

            T toReturn = (T)serializer.Deserialize(reader);
            reader.Close();
            reader.Dispose();
            return toReturn;
        }
        /// <summary>
        /// Désérialisation d'une chaine de caractères vers le type T
        /// </summary>
        /// <param name="str"></param>
        /// <param name="t"></param>
        /// <returns></returns>
        public static object Deserialize(String str, Type t)
        {
            XmlSerializer serializer = new XmlSerializer(t);
            StringReader reader = new StringReader(str);

            object toReturn = serializer.Deserialize(reader);
            reader.Close();
            reader.Dispose();
            return toReturn;
        }
        #endregion
    }
}
